package com.shali.wechat.order.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.shali.wechat.order.client.ProductFeignClient;
import com.shali.wechat.order.converter.OrderForm2OrderDTOConverter;
import com.shali.wechat.order.dto.OrderDTO;
import com.shali.wechat.order.enums.ResultEnum;
import com.shali.wechat.order.exception.OrderException;
import com.shali.wechat.order.form.OrderForm;
import com.shali.wechat.order.service.OrderService;
import com.shali.wechat.order.utils.ResultVOUtil;
import com.shali.wechat.order.vo.ResultVO;
import com.shali.wechat.product.common.DecreaseStockInput;
import com.shali.wechat.product.common.ProductInfoOutput;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ProductFeignClient productFeignClient;
	/**
	 * 1.参数检验
	 * 2.查询商品信息（调用商品微服务）
	 * 3.计算总价
	 * 4.扣库存
	 * 5.订单入库
	 */
	
	@SuppressWarnings("unchecked")
	@PostMapping("/create")
	public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			log.error("【创建订单】参数不挣钱,orderForm={}",orderForm);
			throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),
										bindingResult.getFieldError().getDefaultMessage());
		}
		OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
		if(CollectionUtils.isEmpty(orderDTO.getOrderDetail())) {
			log.error("【创建订单】购物车信息为空");
			throw new OrderException(ResultEnum.CART_EMPTY);
		}
		OrderDTO result = orderService.create(orderDTO);
		Map<String,String> map = new HashMap<>();
		map.put("orderId", result.getOrderId());
		return ResultVOUtil.success(map);
	}
	
	@GetMapping("/getProductList")
	public String getProductInfoList() {
		List<ProductInfoOutput> response = productFeignClient.getProductInfoList(Arrays.asList("157875227953464068"));
		log.info("【response】--->{}",response);
		return "ok";
	}
	
	@GetMapping("/decreaseStock")
	public String decreaseStock() {
		productFeignClient.decreaseStock(Arrays.asList(new DecreaseStockInput("157875227953464068",1)));
		return "ok";
	}
}
